This project implements an intelligent agent system based on Google Agent Development Kit (ADK), specifically designed for querying and providing weather and time information for cities. The system supports both Chinese and English city names and obtains the latest information through external APIs.
此專案實現了一個基於Google Agent Development Kit (ADK)的智能代理系統,專門用於查詢和提供城市的天氣和時間資訊。系統支援中英文城市名稱,並通過外部API獲取最新資訊。
The project contains two main files:
專案包含兩個主要檔案:
This is an initialization file for a Python package, used to make the package correctly importable.
這是一個Python套件的初始化檔案,用於使套件可被正確導入。
#package的初始文件
from . import agent
This short file implements two key functions:
This pattern allows users to access the functionality in the agent module directly through import packagename.
這個簡短的檔案實現了兩個關鍵功能:
這種模式允許用戶通過import packagename的方式直接訪問agent模組中的功能。
This is the main implementation file, containing weather and time query functions as well as the Google ADK agent definition.
這是主要實現檔案,包含了天氣和時間查詢功能以及Google ADK代理的定義。
import os
import requests
import datetime
from zoneinfo import ZoneInfo
from google.adk.agents import Agent
from google.adk.models.lite_llm import LiteLlm
The imported modules include:
導入的模組包括:
# 城市名稱對應表:中文轉英文
CITY_TRANSLATIONS = {
"台北": "Taipei",
"紐約": "New York",
"倫敦": "London",
"東京": "Tokyo",
# 可擴充更多城市
}
This dictionary maps Chinese city names to English names, allowing the system to support Chinese input. Users can use Chinese city names, and the system will automatically convert them to English names that the API can recognize. This dictionary can be expanded with more cities as needed.
這個字典將中文城市名稱映射到英文名稱,使系統能夠支援中文輸入。用戶可以使用中文城市名稱,系統會自動轉換為API能識別的英文名稱。這個字典可以根據需要擴充更多城市。
def fetch_weather_info(city_name: str) -> dict:
"""
查詢指定城市的即時天氣資訊。
支援中文城市名稱,會自動轉換為英文。
"""
if not city_name:
return {
"status": "error",
"error_message": "請提供城市名稱以查詢天氣資訊。"
}
api_key = os.getenv("WEATHER_API_KEY")
api_endpoint = "http://api.weatherapi.com/v1/current.json"
query_city = CITY_TRANSLATIONS.get(city_name, city_name)
try:
response = requests.get(api_endpoint, params={"key": api_key, "q": query_city})
if response.status_code == 200:
data = response.json()
location = data["location"]["name"]
country = data["location"]["country"]
temp_c = data["current"]["temp_c"]
temp_f = data["current"]["temp_f"]
condition = data["current"]["condition"]["text"]
humidity = data["current"]["humidity"]
wind_speed = data["current"]["wind_kph"]
weather_report = (
f"目前{city_name}({country})的天氣為{condition},"
f"溫度 {temp_c}°C({temp_f}°F),"
f"濕度 {humidity}%,風速 {wind_speed} 公里/小時。"
)
return {
"status": "success",
"report": weather_report,
}
else:
return {
"status": "error",
"error_message": f"無法取得「{city_name}」的天氣資訊。API 回應代碼:{response.status_code},請檢查城市名稱是否正確。"
}
except Exception as e:
return {
"status": "error",
"error_message": f"取得「{city_name}」的天氣資訊時發生錯誤:{str(e)}"
}
This function is used to query weather information for a specified city:
The return value is a dictionary containing status and report (or error_message).
這個函數用於查詢指定城市的天氣資訊:
返回值是一個包含status和report(或error_message)的字典。
def fetch_local_time(city_name: str) -> dict:
"""
查詢指定城市的當前時間。
支援中文城市名稱,會自動轉換為英文。
"""
if not city_name:
return {
"status": "error",
"error_message": "請提供城市名稱以查詢當前時間。"
}
api_key = os.getenv("WEATHER_API_KEY")
api_endpoint = "http://api.weatherapi.com/v1/current.json"
query_city = CITY_TRANSLATIONS.get(city_name, city_name)
try:
response = requests.get(api_endpoint, params={"key": api_key, "q": query_city})
if response.status_code == 200:
data = response.json()
timezone_id = data["location"]["tz_id"]
local_time = data["location"]["localtime"]
time_report = f"目前{city_name}的時間是 {local_time}({timezone_id} 時區)"
return {
"status": "success",
"report": time_report
}
else:
return {
"status": "error",
"error_message": f"無法取得「{city_name}」的時區資訊。API 回應代碼:{response.status_code},請檢查城市名稱是否正確。"
}
except Exception as e:
return {
"status": "error",
"error_message": f"取得「{city_name}」的時間資訊時發生錯誤:{str(e)}"
}
This function is used to query the current time for a specified city:
Similar to the weather query function, the return value is a dictionary containing status and report (or error_message).
這個函數用於查詢指定城市的當前時間:
與天氣查詢函數類似,返回值是一個包含status和report(或error_message)的字典。
# 定義代理
os.environ["OPENAI_API_BASE"] = os.getenv("OPENAI_BASE_URL")
model = os.getenv("CHAT_MODEL", "gpt-4o-mini")
root_agent = Agent(
name="weather_time_agent",
model=LiteLlm(model="openai/" + model),
description="回答有關城市時間和天氣的問題。",
instruction="我將回答您關於城市時間和天氣的問題,請提供城市名稱。",
tools=[fetch_weather_info, fetch_local_time]
)
This part of the code defines an intelligent agent using Google ADK:
This agent can understand user queries and automatically decide which function to call to answer questions about city weather or time.
這部分程式碼定義了使用Google ADK的智能代理:
這個代理能夠理解用戶查詢,並自動決定調用哪個函數來回答關於城市天氣或時間的問題。